package com.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.github.alipay.AlipayConfig;
import com.github.wxpay.IWxPayConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayConstants.SignType;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.util.GetConfig;
import com.util.GsonUtil;
import com.util.StringUtil;
import com.util.WebChatUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/home")
public class MainController extends BaseAction {
    @RequestMapping(value = "/intface",produces="text/html;charset=UTF-8;")
    @ResponseBody
    public String intface(String mathod,String jsonData,HttpServletRequest request){
    	return getHttpJson(mathod,jsonData,request,false);
    }
    /**
	 * index页面 登录，banner
	 * @param request
	 * @return
	 */
    @RequestMapping("/wxindex")
    public ModelAndView wxindex(HttpServletRequest request,String code){
    	ModelAndView md=new ModelAndView("wxindex");
    	String openId=(String) getHttpSession(request).getAttribute(openIdKey);//获取OpenId
    	if(openId!=null&&!"".equals(openId)){
    		md.addObject("openId",openId);
    		return md;
    	}else{
    		if(code==null||"".equals(code)){
    			md.addObject("appid",WebChatUtil.WXAPPID);
    		}else{
    			JsonObject json = WebChatUtil.getUserInfo(code);
    			if(json!=null){
    				openId=json.get("openid").getAsString();
    				getHttpSession(request).setAttribute(openIdKey, openId);
    				if(json.get("nickname")!=null){
    					getHttpSession(request).setAttribute(userNameKey, json.get("nickname").getAsString());
    				}
    				if(json.get("headimgurl")!=null){
    					getHttpSession(request).setAttribute(userImgKey, json.get("headimgurl").getAsString());
    				}
    				md.addObject("openId",openId);
    			}else{
    				md.addObject("code",code);
    			}
    		}
    	}
        return md;
    }
    @RequestMapping("/wxorder")
    public ModelAndView wxorder(HttpServletRequest request,String code){
    	ModelAndView md=new ModelAndView("wxorder");
    	if(code!=null){
    		JsonObject json = WebChatUtil.getUserInfo(code);
    		if(json!=null){
    			String openId=json.get("openid").getAsString();
    			getHttpSession(request).setAttribute(openIdKey, openId);
    			if(json.get("nickname")!=null){
    				getHttpSession(request).setAttribute(userNameKey, json.get("nickname").getAsString());
    			}
    			if(json.get("headimgurl")!=null){
    				getHttpSession(request).setAttribute(userImgKey, json.get("headimgurl").getAsString());
    			}
    			//存登录信息
    			String memKey=getMemKey(openId);
				if(memKey!=null&&!"".equals(memKey)){
					setMemKey(request,memKey);
				}
    		}
    		md=new ModelAndView("redirect:/order/getAllOrderList");
    	}else{
    		md.addObject("appid",WebChatUtil.WXAPPID);
    	}
    	return md;
    }
    @RequestMapping("/wxmember")
    public ModelAndView wxmember(HttpServletRequest request,String code){
    	ModelAndView md=new ModelAndView("wxmember");
    	if(code!=null){
    		JsonObject json = WebChatUtil.getUserInfo(code);
    		if(json!=null){
    			String openId=json.get("openid").getAsString();
    			getHttpSession(request).setAttribute(openIdKey, openId);
    			if(json.get("nickname")!=null){
    				getHttpSession(request).setAttribute(userNameKey, json.get("nickname").getAsString());
    			}
    			if(json.get("headimgurl")!=null){
    				getHttpSession(request).setAttribute(userImgKey, json.get("headimgurl").getAsString());
    			}
    			//存登录信息
    			String memKey=getMemKey(openId);
				if(memKey!=null&&!"".equals(memKey)){
					setMemKey(request,memKey);
				}
    		}
    		md=new ModelAndView("redirect:/member/memberCenter");
    	}else{
    		md.addObject("appid",WebChatUtil.WXAPPID);
    	}
    	return md;
    }
	/**
	 * index页面 登录，banner
	 * @param request
	 * @param city
	 * @param cityName
	 * @param startDate
	 * @param endDate
	 * @param lng
	 * @param lat
	 * @return
	 */
    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request,String city,String cityName,String startDate,String endDate,String lng,String lat,String code,String openId){
    	ModelAndView md=new ModelAndView("index");
    	//首次通过微信公众号菜单进入会传入code，进而获得openid存session
    	if(code!=null){
    		JsonObject json = WebChatUtil.getUserInfo(code);
    		if(json!=null){
    			openId=json.get("openid").getAsString();
    			getHttpSession(request).setAttribute(openIdKey, openId);
    			if(json.get("nickname")!=null){
    				getHttpSession(request).setAttribute(userNameKey, json.get("nickname").getAsString());
    			}
    			if(json.get("headimgurl")!=null){
    				getHttpSession(request).setAttribute(userImgKey, json.get("headimgurl").getAsString());
    			}
    			//存登录信息
    			String memKey=getMemKey(openId);
				if(memKey!=null&&!"".equals(memKey)){
					setMemKey(request,memKey);
				}
    		}
    	}else if(openId!=null){
    		getHttpSession(request).setAttribute(openIdKey, openId);
    	}
    	List<Map<String,Object>> citys=new ArrayList<Map<String,Object>>();
    	String cityJson=getHttpJson("Logistics/ZDK/GetCityList",null,request,false);
    	if(cityJson!=null){
    		Map<String,Object> map=GsonUtil.fromJson(cityJson,new TypeToken<Map<String, Object>>(){}.getType());
    		if(map.get("stateID")!=null &&(Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0){
    			citys=(List<Map<String, Object>>) map.get("dataList");
    		}
    		getHttpSession(request).setAttribute("citys",cityJson);
    	}
    	if(city==null||"".equals(city)){
    		if(citys.size()>0){
    			city=(String) citys.get(0).get("Code");
    			cityName=(String) citys.get(0).get("AreaName");
    		}else{
    			city="";
    			cityName="";
    		}
    	}
    	md.addObject("citys",citys);
//    	String ticket=(String) getHttpSession(request).getAttribute(tokenKey);
//    	if(ticket==null){
//    		ticket=WebChatUtil.getJsTicket();
//    		getHttpSession(request).setAttribute(tokenKey,ticket);
//    	}

//    	String url=GetConfig.getString("base_url")+(request.getRequestURI()).substring(1);
    	String url=GetConfig.getString("base_url")+"home/index";
    	Map<String, String> map = WebChatUtil.getJsapi(url);
    	
    	md.addObject("wxMap",map);
    	md.addObject("url",url);
    	md.addObject("city",city);
    	md.addObject("cityName",cityName);
    	md.addObject("startDate",startDate);
    	md.addObject("endDate",endDate);
    	md.addObject("lng",lng);
    	md.addObject("lat",lat);
    	md.addObject("openId",openId);
        return md;
    }
	/**
	 * 获取开通城市
	 * @param request
	 * @param url
	 * @param startDate
	 * @param endDate
	 * @param lng
	 * @param lat
	 */
    @RequestMapping("/gardenCity")
    public ModelAndView gardenCity(HttpServletRequest request,String url,String startDate,String endDate,String lng,String lat){
    	ModelAndView md=new ModelAndView("/gardenCity");
    	List<Map<String,Object>> citys=new ArrayList<Map<String,Object>>();
    	String cityJson=(String) getHttpSession(request).getAttribute("citys");
    	if(cityJson==null||"".equals(cityJson)){
    		 cityJson=getHttpJson("Logistics/ZDK/GetCityList",null,request,false);
    	}
    	//String cityJson=getHttpJson("Logistics/ZDK/GetCityList",null,request,false);
    	if(cityJson!=null){
    		Map<String,Object> map=GsonUtil.fromJson(cityJson,new TypeToken<Map<String, Object>>(){}.getType());
    		if(map.get("stateID")!=null && (Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0){
    			citys=(List<Map<String, Object>>) map.get("dataList");
    		}
    	}
//    	String ticket=(String) getHttpSession(request).getAttribute(tokenKey);
//    	if(ticket==null){
//    		ticket=WebChatUtil.getJsTicket();
//    		getHttpSession(request).setAttribute(tokenKey,ticket);
//    	}
    	Map<String, String> map = WebChatUtil.getJsapi(GetConfig.getString("base_url")+"home/gardenCity");
    	md.addObject("wxMap",map);
    	md.addObject("citys",citys);
    	md.addObject("startDate",startDate);
    	md.addObject("endDate",endDate);
    	md.addObject("lng",lng);
    	md.addObject("lat",lat);
    	md.addObject("url",url);
        return md;
    }
	/**
	 * 点击下单，获取此时间段可用的房间列表
	 * @param request
	 * @param city
	 * @param cityName
	 * @param startDate
	 * @param endDate
	 * @param neight
	 * @param lng
	 * @param lat
	 * @return
	 */
    @RequestMapping("/hotelList")
    public ModelAndView hotelList(HttpServletRequest request,String city,String cityName,String startDate,String endDate,
                                  String lng,String lat){
    	ModelAndView md=new ModelAndView("hotelList");

    	JSONObject json=new JSONObject();
		List<Map<String,Object>> holtels=new ArrayList<Map<String,Object>>();
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("CityCode",city);
		if(!StringUtil.isNullOrEmpty(lng)&&!StringUtil.isNullOrEmpty(lat)){
			promap.put("Lng",new BigDecimal(lng));
			promap.put("Lat",new BigDecimal(lat));
		}
		promap.put("PageIndex","1");
		promap.put("PageSize","20");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Date EndDate = new Date();
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
			promap.put("EndDate",EndDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String hotelJson=getHttpJson("Logistics/HOS/GetHotelInfo",GsonUtil.toJson(promap),request,false);
		if(hotelJson!=null){
			Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
			if(map.get("stateID")!=null && (Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0 && !"".equals(map.get("dataList"))){
				holtels=(List<Map<String, Object>>) map.get("dataList");
				for(Map<String, Object> holtel:holtels){
					if(holtel.get("StartPrice").toString().indexOf(".0")>-1){
						holtel.put("StartPrice",holtel.get("StartPrice").toString().substring(0,holtel.get("StartPrice").toString().indexOf(".0")));
					}
					if(holtel.get("BreakfastPrice").toString().indexOf(".0")>-1){
						holtel.put("BreakfastPrice",holtel.get("BreakfastPrice").toString().substring(0,holtel.get("BreakfastPrice").toString().indexOf(".0")));
					}
					Double Distance=(Double)holtel.get("Distance");
					if(Distance!=null&&Distance!=0){
						if(Distance>10000000){
							holtel.put("Distance",new BigDecimal(Distance/10000000).setScale(2, BigDecimal.ROUND_HALF_UP)+"万公里");
						}else if(Distance>1000){
							holtel.put("Distance",new BigDecimal(Distance/1000).setScale(2, BigDecimal.ROUND_HALF_UP)+"公里");
						}else{
							holtel.put("Distance",Distance+"米");
						}
					}else{
						holtel.put("Distance","em");
					}
				}
			}
		}
		json.put("holtels",holtels);
		
    	md.addObject("loadDataJson",GsonUtil.toJson(holtels));
    	md.addObject("cityName",cityName);
    	md.addObject("city",city);
    	md.addObject("startDate",startDate);
    	md.addObject("endDate",endDate);
    	md.addObject("lng",lng);
    	md.addObject("lat",lat);
    	return md;
    }

	/**
	 * 点击下单，获取此时间段可用的房间列表ajax
	 * @param request
	 * @param city
	 * @param cityName
	 * @param startDate
	 * @param endDate
	 * @param lng
	 * @param lat
	 * @return
	 */
	@RequestMapping("/hotelListAjax")
    @ResponseBody
	public JSONObject hotelListAjax(HttpServletRequest request, String city,String cityName, String startDate, String endDate,
									String lng, String lat, String page, String pageSize){
		JSONObject json=new JSONObject();
		List<Map<String,Object>> holtels=new ArrayList<Map<String,Object>>();
		Map<String,Object> promap=new HashMap<String,Object>();
		lng=lng.replace("key", "");
		lat=lat.replace("key", "");
		promap.put("CityCode",city);
		if(!StringUtil.isNullOrEmpty(lng)&&!StringUtil.isNullOrEmpty(lat)){
			promap.put("Lng",new BigDecimal(lng));
			promap.put("Lat",new BigDecimal(lat));
		}
		if(page==null){
			page="1";
		}
		if(pageSize==null){
			pageSize="20";
		}
		promap.put("PageIndex",page);
		promap.put("PageSize",pageSize);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Date EndDate = new Date();
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
			promap.put("EndDate",EndDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String hotelJson=getHttpJson("Logistics/HOS/GetHotelInfo",GsonUtil.toJson(promap),request,false);
		if(hotelJson!=null){
			Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
			if(map.get("stateID")!=null && (Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0 && !"".equals(map.get("dataList"))){
				holtels=(List<Map<String, Object>>) map.get("dataList");
				for(Map<String, Object> holtel:holtels){
					if(holtel.get("StartPrice").toString().indexOf(".0")>-1){
						holtel.put("StartPrice",holtel.get("StartPrice").toString().substring(0,holtel.get("StartPrice").toString().indexOf(".0")));
					}
					if(holtel.get("BreakfastPrice").toString().indexOf(".0")>-1){
						holtel.put("BreakfastPrice",holtel.get("BreakfastPrice").toString().substring(0,holtel.get("BreakfastPrice").toString().indexOf(".0")));
					}
					Double Distance=(Double)holtel.get("Distance");
					if(Distance!=null&&Distance!=0){
						if(Distance>10000000){
							holtel.put("Distance",new BigDecimal(Distance/10000000).setScale(2, BigDecimal.ROUND_HALF_UP)+"万公里");
						}else if(Distance>1000){
							holtel.put("Distance",new BigDecimal(Distance/1000).setScale(2, BigDecimal.ROUND_HALF_UP)+"公里");
						}else{
							holtel.put("Distance",Integer.parseInt(Distance+"")+"米");
						}
					}else{
						holtel.put("Distance","em");
					}
				}
			}
		}
		json.put("holtels",holtels);
		json.put("cityName",cityName);
		json.put("city",city);
		json.put("startDate",startDate);
		json.put("endDate",endDate);
		json.put("lng",lng);
		json.put("lat",lat);
		return json;
	}
	/**
	 * 通过hotelKey查询详情（需登录，会员看到的价格可能不一样）
	 * @param request
	 * @param hotelKey
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("/hotelDetails")
	public ModelAndView hotelDetails(HttpServletRequest request,String hotelKey,String startDate,String endDate,String city,String cityName,String lng,String lat,String type){
		ModelAndView md = new ModelAndView("hotelDetails");
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("HotelKey",hotelKey);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		String HotelName="酒店详情";
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
			promap.put("EndDate",EndDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String hotelDetailJson=getHttpJson("Logistics/HOS/GetRoomsInfo",GsonUtil.toJson(promap),request,true);
		if("gotoRegister".equals(hotelDetailJson)){
			md=new ModelAndView("redirect:/home/gotoRegister");
			md.addObject("namespase","home");
			md.addObject("url","hotelDetails");
		}else if(hotelDetailJson!=null){
			Map<String,Object> map=GsonUtil.fromJson(hotelDetailJson,new TypeToken<Map<String, Object>>(){}.getType());
			if(map.get("stateID")!=null && (Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0 && !"".equals(map.get("dataList"))){
				Map<String,Object> dataMap=(Map<String, Object>) map.get("dataList");
				md.addObject("HotelDetail",dataMap);
				double night=(Double) dataMap.get("NightNum");
				dataMap.put("NightNum",(int)night);
				double commentNum=(Double) dataMap.get("CommentNum");
				dataMap.put("commentNum",(int)commentNum);
				if(dataMap!=null){
					HotelName=(String)dataMap.get("HotelName");
				}
                double grade=(Double) dataMap.get("Grade");
                dataMap.put("grade",(int)grade);
                if(map.get("TurnPicList").equals("")){
                    md.addObject("TurnPicList",null);
                }else{
                    md.addObject("TurnPicList",map.get("TurnPicList"));
                }

                if(map.get("RoomTypeList").equals("")){
                    md.addObject("RoomTypeList",null);
                }else{
                    List<Map<String,Object>> RoomTypeList=(List<Map<String, Object>>) map.get("RoomTypeList");
                    for(Map<String,Object> RoomType:RoomTypeList){
                        double id=(Double) RoomType.get("ID");
                        double cheapest=0;

                        double RackRate=(Double) RoomType.get("RackRate");
                        double MemberPrice=(Double) RoomType.get("MemberPrice");
                        double NowPayPrice=(Double) RoomType.get("NowPayPrice");
                        String RackRateStr = RackRate+"";
                        String cheapestStr = cheapest+"";
                        String MemberPriceStr = MemberPrice+"";
                        String NowPayPriceStr = NowPayPrice+"";
                        RoomType.put("ID",(int)id);
                        if(RackRateStr.indexOf(".0")>-1){
                            RackRateStr = RackRateStr.substring(0,RackRateStr.indexOf(".0"));
                            RoomType.put("RackRate",RackRateStr);
                        }
                        if(MemberPriceStr.indexOf(".0")>-1){
                            MemberPriceStr = MemberPriceStr.substring(0,MemberPriceStr.indexOf(".0"));
                            RoomType.put("MemberPrice",MemberPriceStr);
                        }
                        if(NowPayPriceStr.indexOf(".0")>-1){
                            NowPayPriceStr = NowPayPriceStr.substring(0,NowPayPriceStr.indexOf(".0"));
                            RoomType.put("NowPayPrice",NowPayPriceStr);
                        }


                        if(MemberPrice==0){
                            cheapestStr=NowPayPriceStr;
                        }else if(NowPayPrice==0){
                            cheapestStr=MemberPriceStr;
                        }else{
                            if(MemberPrice>=NowPayPrice){
                                cheapestStr=NowPayPriceStr;
                            }else{
                                cheapestStr=MemberPriceStr;
                            }
                        }
                        if(cheapest==0){
                            cheapestStr=RackRateStr;
                        }

                        if(cheapestStr.indexOf(".0")>-1){
                            cheapestStr = cheapestStr.substring(0,cheapestStr.indexOf(".0"));
                        }
                        RoomType.put("Cheapest", cheapestStr);
                    }
                    md.addObject("RoomTypeList",RoomTypeList);
                }

			}
//	    	String ticket=(String) getHttpSession(request).getAttribute(tokenKey);
//	    	if(ticket==null){
//	    		ticket=WebChatUtil.getJsTicket();
//	    		getHttpSession(request).setAttribute(tokenKey,ticket);
//	    	}
	    	Map<String, String> wxMap = WebChatUtil.getJsapi(GetConfig.getString("base_url")+"home/hotelDetails");
	    	md.addObject("wxMap",wxMap);
	    	md.addObject("type",type);
	    	md.addObject("link",GetConfig.getString("base_url")+"member/shareHtml?memKey="+getMemKey(request));
		}
		md.addObject("hotelName",HotelName);
		md.addObject("startDate",startDate);
		md.addObject("endDate",endDate);
		md.addObject("hotelKey",hotelKey);
    	md.addObject("cityName",cityName);
    	md.addObject("city",city);
    	md.addObject("lng",lng);
    	md.addObject("lat",lat);
		return md;
	}
	/**
	 * 预定房间
	 * @param request
	 * @return
	 */
	@RequestMapping("/orderFilling")
    public ModelAndView orderFilling(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,
    		Integer nightNum,String hotleName,String roomName,String city,String cityName,String lng,String lat,String type){
		ModelAndView md = new ModelAndView("orderFilling");
		Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	String hotelJson=getHttpJson("Logistics/HOS/GetWriteOrdInfo",GsonUtil.toJson(promap),request,true);
			if("gotoRegister".equals(hotelJson)){
				md=new ModelAndView("redirect:/home/gotoRegister");
			}else if(hotelJson!=null){
	    		Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
				if((Double)map.get("stateID")==0&&(Double)map.get("businessState")==0){
					String totalPriceStr = map.get("TotalPrice").toString();
					if(totalPriceStr.indexOf(".0")>-1){
						totalPriceStr = totalPriceStr.substring(0,totalPriceStr.indexOf(".0"));
						map.put("TotalPrice",totalPriceStr);
					}
                    Object tmp = map.get("dataList");
                    Object PriceDetailList = map.get("PriceDetailList");
                    List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                    if(null!=PriceDetailList){
                        list = (List<Map<String,Object>>)PriceDetailList;
                        if(list.size()>0){
                            for(Map<String,Object> price:list){
                                String dateStr=(String)price.get("CostDate");
                                price.put("DateStr", dateStr.substring(0,(dateStr.indexOf(" "))));
                            }

                        }
                    }

				}
				md.addObject("OrderFilling",map);

	    	}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		md.addObject("memKey",login(request));
		md.addObject("hotelKey",hotelKey);
		md.addObject("reserveType",reserveType);
		md.addObject("roomTypeID",roomTypeID);
		md.addObject("nightNum",nightNum);
		md.addObject("startDate",startDate);
		md.addObject("endDate",endDate);
		md.addObject("hotleName",hotleName);
		md.addObject("roomName",roomName);
		
    	md.addObject("cityName",cityName);
    	md.addObject("city",city);
    	md.addObject("lng",lng);
    	md.addObject("lat",lat);
    	md.addObject("type",type);
    	return md;
    }
    /**
	 * 订单支付页面
	 * @param request
	 * @return
	 */
    @RequestMapping("/orderPayment")
    public ModelAndView orderPayment(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,Integer nightNum,String hotleName,
    		String roomName,String couponCode,String freeRoomCode,Integer delayedNum,String invoiceCode,String remarks,String otherRemarks,Integer roomNum,String guestPhone,String guestList){
    	ModelAndView md= new ModelAndView("orderPayment");
    	Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
					StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	promap.put("CouponCode",couponCode);
	    	promap.put("FreeRoomCode",freeRoomCode);
	    	promap.put("DelayedNum",delayedNum);
	    	promap.put("InvoiceCode",invoiceCode);
	    	if(remarks!=null&&remarks.length()>0){
	    		remarks=remarks.substring(0,remarks.length()-1);
	    	}
	    	promap.put("Remarks",remarks);
	    	promap.put("OtherRemarks",otherRemarks);
	    	promap.put("RoomNum",roomNum);
	    	promap.put("GuestPhone",guestPhone);
	    	List<Map<String,String>> GuestList=new ArrayList<Map<String,String>>();
	    	if(guestList!=null){
	    		String[] guests=guestList.split(",");
	    		for(String guest:guests){
	    			if(guest!=null&&!"".equals(guest)){
	    				Map<String,String> GuestMap=new HashMap<String,String>();
	    				GuestMap.put("GuestName", guest);
	    				GuestMap.put("GuestPhone", "");
	    				GuestList.add(GuestMap);
	    			}
	    		}
	    	}
	    	promap.put("GuestList",GuestList);
	    	String hotelJson=getHttpJson("Logistics/SAL/CreateOrd",GsonUtil.toJson(promap),request,true);
			if("gotoRegister".equals(hotelJson)){
				md=new ModelAndView("redirect:/home/gotoRegister");
			}else if(hotelJson!=null){
	    		Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
				if(map.get("stateID")!=null &&(Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0){
					if(map.get("PayTotal")==null||Double.valueOf((String)map.get("PayTotal"))==0){
						md= new ModelAndView("redirect:/order/getAllOrderList?ordState=1000");
						return md;
					}else{
						md.addObject("orderPayment",map);
					}
				}else{
	    			 md= new ModelAndView("redirect:/home/orderError");
//	    			 md= new ModelAndView("redirect:/order/getAllOrderList?ordState=1000");
	    			 return md;
	    		}

	    	}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		md.addObject("hotelKey",hotelKey);
		md.addObject("reserveType",reserveType);
		md.addObject("roomTypeID",roomTypeID);
		md.addObject("nightNum",nightNum);
		md.addObject("startDate",startDate);
		md.addObject("endDate",endDate);
		md.addObject("hotleName",hotleName);
		md.addObject("roomName",roomName);
    	return md;
    }
    /**
	 * 订单支付页面
	 * @param request
	 * @return
     * @throws UnsupportedEncodingException 
	 */
    @RequestMapping(value = "/orderPayment2",produces="text/html;charset=UTF-8;")
    @ResponseBody
    public String orderPayment2(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,String hotleName,
    		String roomName,String couponCode,String freeRoomCode,Integer delayedNum,String invoiceCode,String remarks,String otherRemarks,Integer roomNum,String guestPhone,String guestList) throws UnsupportedEncodingException{
    	Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
					StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	promap.put("CouponCode",couponCode);
	    	promap.put("FreeRoomCode",freeRoomCode);
	    	promap.put("DelayedNum",delayedNum);
	    	promap.put("InvoiceCode",invoiceCode);
	    	if(remarks!=null&&remarks.length()>0){
	    		remarks=remarks.substring(0,remarks.length()-1);
	    	}
	    	promap.put("Remarks",remarks);
	    	promap.put("OtherRemarks",otherRemarks);
	    	promap.put("RoomNum",roomNum);
	    	promap.put("GuestPhone",guestPhone);
	    	List<Map<String,String>> GuestList=new ArrayList<Map<String,String>>();
	    	if(guestList!=null){
	    		String[] guests=guestList.split(",");
	    		for(String guest:guests){
	    			if(guest!=null&&!"".equals(guest)){
	    				Map<String,String> GuestMap=new HashMap<String,String>();
	    				GuestMap.put("GuestName", guest);
	    				GuestMap.put("GuestPhone", "");
	    				GuestList.add(GuestMap);
	    			}
	    		}
	    	}
	    	promap.put("GuestList",GuestList);
	    	String hotelJson=getHttpJson("Logistics/SAL/CreateOrd",GsonUtil.toJson(promap),request,true);
//	    	if("gotoRegister".equals(hotelJson)){
//				return "gotoRegister";
//			}else if(hotelJson!=null){
//
//	    		Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
//	    		//都为0 不提示messgae
//	    		if((double)map.get("businessState")==0&&(double)map.get("stateID")==0){
//					if(map.get("PayTotal")==null||Double.valueOf((String)map.get("PayTotal"))==0){
//						return "gotoOrderList";
//					}else{
//						return hotelJson;
//					}
//	    		}else{
//					String msgInfo= (String)map.get("msgInfo");
//					return msgInfo;
//				}
//
//	    	}
	    	return hotelJson;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
    }
    /**
	 * 订单支付页面
	 * @param request
	 * @return
	 */
    @RequestMapping("/orderPayment1")
    public ModelAndView orderPayment1(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,Integer nightNum,String hotleName,
    		String roomName,String couponCode,String freeRoomCode,Integer delayedNum,String invoiceCode,String remarks,String otherRemarks,Integer roomNum,String guestPhone,String guestList){
    	ModelAndView md= new ModelAndView("orderPayment");
    	Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
					StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	promap.put("CouponCode",couponCode);
	    	promap.put("FreeRoomCode",freeRoomCode);
	    	promap.put("DelayedNum",delayedNum);
	    	promap.put("InvoiceCode",invoiceCode);
	    	if(remarks!=null&&remarks.length()>0){
	    		remarks=remarks.substring(0,remarks.length()-1);
	    	}
	    	promap.put("Remarks",remarks);
	    	promap.put("OtherRemarks",otherRemarks);
	    	promap.put("RoomNum",roomNum);
	    	promap.put("GuestPhone",guestPhone);
	    	List<Map<String,String>> GuestList=new ArrayList<Map<String,String>>();
	    	if(guestList!=null){
	    		String[] guests=guestList.split(",");
	    		for(String guest:guests){
	    			if(guest!=null&&!"".equals(guest)){
	    				Map<String,String> GuestMap=new HashMap<String,String>();
	    				GuestMap.put("GuestName", guest);
	    				GuestMap.put("GuestPhone", "");
	    				GuestList.add(GuestMap);
	    			}
	    		}
	    	}
	    	promap.put("GuestList",GuestList);
	    	String hotelJson=getHttpJson("Logistics/SAL/CreateOrd",GsonUtil.toJson(promap),request,true);
			if("gotoRegister".equals(hotelJson)){
				md=new ModelAndView("redirect:/home/gotoRegister");
			}else if(hotelJson!=null){
	    		Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
				if(map.get("stateID")!=null &&(Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0){
					if(map.get("PayTotal")==null||Double.valueOf((String)map.get("PayTotal"))==0){
						md= new ModelAndView("redirect:/order/getAllOrderList?ordState=1000");
						return md;
					}else{
						md= new ModelAndView("redirect:/home/orderPaymentDetail?ordCode="+map.get("OrdCode"));
						return md;
					}
				}else{
					md= new ModelAndView("redirect:/home/orderError");
					return md;
				}
	    	}
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return md;
    }
    /**
	 * 订单支付页面
	 * @param request
	 * @return
	 */
    @RequestMapping("/orderError")
    public ModelAndView orderPayment1(HttpServletRequest request){
    	ModelAndView md= new ModelAndView("orderError");
    	return md;
    }
    /**
	 * 订单支付页面
	 * @param request
	 * @return
	 */
    @RequestMapping("/orderPaymentDetail")
    public ModelAndView orderPaymentDetail(HttpServletRequest request,String ordCode){
    	ModelAndView md= new ModelAndView("orderPayment");
        if(ordCode==null){
            md=new ModelAndView("redirect:/home/index");
            return md;
        }else{
        	Map<String,Object> promap = new HashMap<String,Object>();
        	promap.put("OrdCode",ordCode);
        	String orderJson=getHttpJson("Logistics/SAL/QueryOrdOfCode",GsonUtil.toJson(promap),request,true);
        	if("gotoRegister".equals(orderJson)){
        		md=new ModelAndView("redirect:/home/gotoRegister");
        		return md;
        	}
        	if(orderJson!=null){
        		Map<String,Object> map=GsonUtil.fromJson(orderJson,new TypeToken<Map<String, Object>>(){}.getType());
				if((Double)map.get("stateID")==0 &&(Double)map.get("businessState")==0){
					Object tmp = map.get("dataList");
					Object PriceDetailList = map.get("PriceDetailList");
					List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
					if(!"".equals(tmp)){
						list = (List<Map<String,Object>>)tmp;
						Map<String,Object> map1=new HashMap<String,Object>();
						if(list.size()>0){
							double payTimeStr = (Double)list.get(0).get("PayTime");
							Integer PayTime = (int)payTimeStr;
							String startDate=(String)(list.get(0).get("ArrivalsTime"));
							String endDate=(String)(list.get(0).get("CheckOutTime"));
							md.addObject("startDate",startDate.substring(0,(startDate.indexOf(" "))));
							md.addObject("endDate",endDate.substring(0,(endDate.indexOf(" "))));
							md.addObject("hotleName",list.get(0).get("HotelName"));
							md.addObject("roomName",list.get(0).get("RoomType"));
							md.addObject("PayTime",PayTime);
							map1.put("TotalSettlementShow",list.get(0).get("TotalSettlement"));
							map1.put("PayTotal",list.get(0).get("PayTotal"));
							map1.put("OrdCode",list.get(0).get("Code"));
							md.addObject("orderPayment",map1);
						}
					}
                    if(!"".equals(PriceDetailList)){
                        list = (List<Map<String,Object>>)PriceDetailList;
                        if(list.size()>0){
                            double num = Double.parseDouble(list.get(0).get("RoomNum").toString());
                            md.addObject("roomNum",(int)num);
                        }
                    }
				}


        	}else{
        		md=new ModelAndView("redirect:/home/index");
                return md;
        	}
        }
    	return md;
    }

	/**
	 * 前往微信注册页面
	 */
    @RequestMapping("/gotoRegister")
	public ModelAndView gotoRegister(HttpServletRequest request,String code,String url,String namespase){
    	ModelAndView md= new ModelAndView("gotoRegister");
    	//判断是否存有openId，如果未存，判断是否传code如果没有返回error页面
    	//如果存在openId，正常返回页面
    	String getOpenid="no";
		if(getHttpSession(request).getAttribute(openIdKey)==null){
			if(code!=null){
				JsonObject json = WebChatUtil.getUserInfo(code);
				if(json!=null){
	    			String openId=json.get("openid").getAsString();
	    			String userName=json.get("nickname").getAsString();
	    			String userImg=json.get("headimgurl").getAsString();
	    			getHttpSession(request).setAttribute(openIdKey, openId);
	    			getHttpSession(request).setAttribute(userNameKey, userName);
	    			getHttpSession(request).setAttribute(userImgKey, userImg);
					//存登录信息
					String memKey=getMemKey(openId);
					if(memKey!=null&&!"".equals(memKey)){
						setMemKey(request,memKey);
					}
				}else{
					return new ModelAndView("error");//无法获取openbId页面
				}
			}else{
				getOpenid="yes";
				md.addObject("appid",WebChatUtil.WXAPPID);
			}
		}
		md.addObject("getOpenid",getOpenid);
		md.addObject("userName",getHttpSession(request).getAttribute(userNameKey));
		md.addObject("userImg",getHttpSession(request).getAttribute(userImgKey));
		String returnUrl="home/index";
		if(url!=null){
			returnUrl=namespase+"/"+url;
		}
		md.addObject("url",returnUrl);
		if("hotelDetails".equals(url)){
			md.addObject("startDate",request.getParameter("startDate"));
			md.addObject("endDate",request.getParameter("endDate"));
			md.addObject("hotelKey",request.getParameter("hotelKey"));
	    	md.addObject("cityName",request.getParameter("cityName"));
	    	md.addObject("city",request.getParameter("city"));
	    	md.addObject("lng",request.getParameter("lng"));
	    	md.addObject("lat",request.getParameter("lat"));
		}
		return md;
	}
	/**
	 * 微信注册
	 * @param Phone 电话号码
	 * @param Captcha 验证码
	 * @param UnionID UnionID(暂时不用)
	 * @return
	 */
    @RequestMapping(value = "/register",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String weChatMemRegister(HttpServletRequest request,String Phone,String Captcha,String UnionID,String OpenId){
		//通过缓存获取OpenId
		if(OpenId==null){
			if(getHttpSession(request).getAttribute(openIdKey)!=null){
				OpenId=(String) getHttpSession(request).getAttribute(openIdKey);
			}else{
				return "error";//无法获取openbId页面
			}
		}
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("Phone",Phone);
		promap.put("Captcha",Captcha);
		promap.put("OpenId",OpenId);
		promap.put("UnionID","");
		String json=getHttpJson("Logistics/MEM/WeChatMemRegister",GsonUtil.toJson(promap),request,false);
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			String memKey=(String) map.get("MemKey");
			if(memKey!=null&&!"".equals(memKey)){
				setMemKey(request,memKey);
				return "success";
			}else{
				return "注册失败！";//注册失败
			}
		}else{
			return "注册失败！";
		}
	}
    /**
	 * 获取验证码
	 * @param Phone 电话号码
	 * @return
	 */
    @RequestMapping(value = "/applySMS",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String applySMS(HttpServletRequest request,String Phone){
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("Phone",Phone);
		String json=getHttpJson("Logistics/MEM/ApplySMS",GsonUtil.toJson(promap),request,false);
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			double stateID=(Double) map.get("stateID");
			double businessState=(Double) map.get("businessState");
			if(stateID==0 && businessState==0){
				return "success";
			}else{
				return (String)map.get("msgInfo");
			}
		}else{
			return "获取失败！";
		}
	}
	/**
	 * 支付页选择发票
	 * @return
	 */
	@RequestMapping("/invoice")
    public ModelAndView invoice(HttpServletRequest request,Boolean needInvoice){
		ModelAndView md= new ModelAndView("invoice");
		String json=getHttpJson("Logistics/MEM/GetMemInvoiceList",null,request,false);
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			if(map!=null&&map.get("dataList")!=null){
				md.addObject("dataList",map.get("dataList"));
			}
		}
		if(needInvoice==null){
			md.addObject("needInvoice",false);
		}else{
			md.addObject("needInvoice",needInvoice);
		}
    	return md;
    }
	/**
	 * 支付页选择优惠券
	 * @return
	 */
    @RequestMapping("/coupon")
    public ModelAndView coupon(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,Integer roomNum){
    	ModelAndView md= new ModelAndView("coupon");
		Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	promap.put("RoomNum",roomNum);
	    	String json=getHttpJson("Logistics/HOS/GetCouponList",GsonUtil.toJson(promap),request,true);
	    	if(json!=null){
				List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
				Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
				if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
					list = (List<Map<String,Object>>)map.get("dataList");
					if(list.size()>0){
						for(int i =0;i<list.size();i++){
							String EndDateStr = list.get(i).get("EndDate").toString();
							list.get(i).put("EndDate", EndDateStr.substring(0,EndDateStr.indexOf(" ")));
						}
					}
					md.addObject("dataList",list);
				}

			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		md.addObject("title","优惠券");
		md.addObject("type","coupon");
    	return md;
    }
    /**
     * 支付页选择免房券
     * @return
     */
    @RequestMapping("/freeRoom")
    public ModelAndView freeRoom(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,Integer roomNum){
    	ModelAndView md= new ModelAndView("coupon");
		Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	promap.put("RoomNum",roomNum);
	    	String json=getHttpJson("Logistics/HOS/GetFreeRoomList",GsonUtil.toJson(promap),request,true);
	    	if(json!=null){
				Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
				if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
					md.addObject("dataList",map.get("dataList"));
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		md.addObject("title","免房券");
		md.addObject("type","free");
    	return md;
    }
    /**
     * 支付页选择延时券
     * @return
     */
    @RequestMapping("/delayed")
    public ModelAndView delayed(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID){
    	ModelAndView md= new ModelAndView("coupon");
		Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	String json=getHttpJson("Logistics/HOS/GetCouponList",GsonUtil.toJson(promap),request,true);
	    	if(json!=null){
				Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
				if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
					md.addObject("dataList",map.get("dataList"));
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return md;
    }
	/**
	 * 支付页选择联系人
	 * @return
	 */
    @RequestMapping("/occupant")
    public ModelAndView occupant(HttpServletRequest request,String memKey,String checkedMsg,String type){
		ModelAndView md= new ModelAndView("occupant");
		String json=getHttpJson("Logistics/MEM/GetMemCheckInPeo",null,request,false);
		if(checkedMsg==null||"".equals(checkedMsg)){checkedMsg="no";}
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
				md.addObject("dataList",map.get("dataList"));
			}
		}
		md.addObject("memKey",memKey);
		md.addObject("checkedMsg",checkedMsg);
		md.addObject("type",type);
    	return md;
    }
	/**
	 * 计算可用房间数
	 * @return
	 */
    @RequestMapping(value = "/getSurplusRoomNum",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String weChatMemRegister(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,Integer roomTypeID,Integer roomNum){
		Map<String,Object> promap=new HashMap<String,Object>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try{
			promap.put("HotelKey",hotelKey);
			promap.put("ReserveType",reserveType);
			promap.put("RoomTypeID",roomTypeID);
			promap.put("RoomNum",roomNum);
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
			promap.put("EndDate",EndDate);
			String json=getHttpJson("Logistics/HOS/GetSurplusRoomNum",GsonUtil.toJson(promap),request,false);
			if(json!=null){
				Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
				if((Double)map.get("stateID")==0  &&(Double)map.get("businessState")==0){
					String enable=(String) map.get("Enable");
					int surplusRoomNum=Integer.parseInt((String)map.get("SurplusRoomNum"));
					if("True".equals(enable)&&surplusRoomNum>0){
						return "success";
					}else{
						return "noRoom";
					}
				}else{
					return map.get("msgInfo").toString();
				}

			}else{
				return "error";
			}
		}catch(Exception e){
			e.printStackTrace();
			return "error";
		}

	}
	/**
	 * 支付订单
	 * @return
	 */
    @RequestMapping(value = "/paymentOrd",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String paymentOrd(HttpServletRequest request,String OrdCode,Integer PaymentType){
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("PaymentType",PaymentType);
		promap.put("OrdCode",OrdCode);
		String json=getHttpJson("Logistics/SAL/PaymentOrd",GsonUtil.toJson(promap),request,false);
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			if((Double)map.get("stateID")==0  &&(Double)map.get("businessState")==0){
				return "success";
			}else{
				return (String)map.get("msgInfo");
			}
		}else{
			return "支付失败！";
		}
	}
	
	/**
	 * 微信支付
	 * @return
	 */
    @RequestMapping(value = "/paymentOrdWX",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String paymentOrdWX(HttpServletRequest request,String OrdCode,String money){
		Map<String,Object> result=new HashMap<String,Object>();
		try {
			IWxPayConfig config = new IWxPayConfig();
			//TODO 微信支付代码
//			WXPay wxpay = new WXPay(config);
//			//金额转化为分为单位
//		    float sessionmoney = Float.parseFloat(money);
//		    String finalmoney = String.format("%.2f", sessionmoney);
//		    finalmoney = finalmoney.replace(".", "");
//	        int intMoney = Integer.parseInt(money);
//            //随机数
//            String nonce_str = WXPayUtil.generateNonceStr();
//            //商品描述
//            String body = "雅客小镇-酒店预订";
//            //总金额以分为单位，不带小数点
//            int total_fee = intMoney;
//            //订单生成的机器 IP
//            String spbill_create_ip = request.getRemoteAddr();
//
//            SortedMap<String, String> packageParams = new TreeMap<String, String>();
//            packageParams.put("nonce_str", nonce_str);
//            packageParams.put("body", body);
//            packageParams.put("out_trade_no", OrdCode);
//            packageParams.put("total_fee", total_fee+"");
//            packageParams.put("spbill_create_ip", spbill_create_ip);
//            packageParams.put("trade_type", "JSAPI");
//            packageParams.put("openid", (String)getHttpSession(request).getAttribute(openIdKey));
//            Map<String, String> resp = wxpay.unifiedOrder(packageParams);
//			System.out.println(resp);
//			if(resp!=null&&"SUCCESS".equals(resp.get("result_code"))){
//				Map<String,String> finalpackage=new HashMap<String,String>();
//				String prepay_id =resp.get("prepay_id");
//				String packages = "prepay_id="+prepay_id;;//订单详情扩展字符串
//				finalpackage.put("appId", config.getAppID());//公众号appid
//				finalpackage.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));
//				finalpackage.put("nonceStr", WXPayUtil.generateNonceStr()); //随机数
//				finalpackage.put("package", packages);
//				//可替换成MD5加密
//				finalpackage.put("signType",WXPayConstants.HMACSHA256);
//				String sing=WXPayUtil.generateSignature(finalpackage, config.getKey(), SignType.HMACSHA256);
//				finalpackage.put("sing",sing);
//				result.put("code", 1);
//				result.put("result", finalpackage);
//			}else{
//				result.put("code", -1);
//			}
			
			Map<String,Object> promap=new HashMap<String,Object>();
			promap.put("PaymentType",5);
			promap.put("OrdCode",OrdCode);
			String json=getHttpJson("Logistics/SAL/PaymentOrd",GsonUtil.toJson(promap),request,false);
			if(json!=null){
				Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
				double stateID=(Double) map.get("stateID");
				double businessState=(Double) map.get("businessState");
				if(stateID==0 && businessState==0&&  map.get("PrepayId")!=null){
					Map<String,Object> prepay=(Map<String, Object>) map.get("PrepayId");
					String prepay_id=(String) prepay.get("prepayid");
					Map<String,String> finalpackage=new HashMap<String,String>();
					String packages = "prepay_id="+prepay_id;//订单详情扩展字符串
					finalpackage.put("appId", (String)prepay.get("appid"));//公众号appid  
					finalpackage.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));  
					finalpackage.put("nonceStr", WXPayUtil.generateNonceStr()); //随机数 
					finalpackage.put("package", packages);
					finalpackage.put("signType",WXPayConstants.MD5);
					String sign=WXPayUtil.generateSignature(finalpackage, config.getKey(), SignType.MD5);
					finalpackage.put("sign",sign);
					finalpackage.put("prepay_id",prepay_id);
					result.put("code", 1);
					result.put("result", finalpackage);
//					result.put("code", 1);
//					result.put("result", prepay);
				}else{
					result.put("code", -1);
				}
			}else{
				result.put("code", -1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", -1);
		}
		return GsonUtil.toJson(result);
	}
    /**
	 * 支付宝支付
	 * @return
	 */
    @RequestMapping(value = "/paymentOrdAi",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String paymentOrdAi(HttpServletRequest request,String OrdCode){
		Map<String,Object> result=new HashMap<String,Object>();
		try {
			Map<String,Object> promap=new HashMap<String,Object>();
			promap.put("PaymentType",6);
			promap.put("OrdCode",OrdCode);
			String json=getHttpJson("Logistics/SAL/PaymentOrd",GsonUtil.toJson(promap),request,false);
			if(json!=null){
				Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
				double stateID=(Double) map.get("stateID");
				if(stateID==0 && (Double)map.get("businessState")==0 && map.get("PaymentAmount")!=null){
					result.put("code", 1);
					result.put("result", map.get("PaymentAmount"));
				}else{
					result.put("code", -1);
				}
			}else{
				result.put("code", -1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", -1);
		}
		return GsonUtil.toJson(result);
	}
    
    @RequestMapping(value = "/aiplay")
    public void aiplay(HttpServletRequest request,HttpServletResponse response,String OrdCode,String money){
		// 商户订单号，商户网站订单系统中唯一订单号，必填
	    String out_trade_no = OrdCode;
		// 订单名称，必填
	    String subject = "雅克小镇-酒店预订";
	    // 付款金额，必填
	    String total_amount=money;
	    // 商品描述，可空
	    String body = "";
	    // 超时时间 可空
	    String timeout_express="2m";
	    // 销售产品码 必填
	    String product_code="QUICK_WAP_WAY";
	    /**********************/
	    // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签     
	    //调用RSA签名方式
	    AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
	    AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
	    // 封装请求支付信息
	    AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
	    model.setOutTradeNo(out_trade_no);
	    model.setSubject(subject);
	    model.setTotalAmount(total_amount);
	    model.setBody(body);
	    model.setTimeoutExpress(timeout_express);
	    model.setProductCode(product_code);
	    alipay_request.setBizModel(model);
	    // 设置异步通知地址
	    alipay_request.setNotifyUrl(AlipayConfig.notify_url);
	    // 设置同步地址
	    alipay_request.setReturnUrl(AlipayConfig.return_url);
	    // form表单生产
	    String form = "";
		try {
			// 调用SDK生成表单
			form = client.pageExecute(alipay_request).getBody();
			response.setContentType("text/html;charset=" + AlipayConfig.CHARSET); 
		    response.getWriter().write(form);//直接将完整的表单html输出到页面 
		    response.getWriter().flush(); 
		    response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    //动态计算价格接口
    @RequestMapping(value = "/getOrdPrice",produces="text/html;charset=UTF-8;")
    @ResponseBody
    public String getOrdPrice(HttpServletRequest request,String hotelKey,String startDate,String endDate,Integer reserveType,
    		Integer roomTypeID,Integer roomNum,String couponCode,String freeRoomCode) {
		Map<String,Object> promap=new HashMap<String,Object>();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
		Date StartDate = new Date();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(StartDate);
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		Date EndDate=calendar.getTime(); //这个时间就是日期往后推一天的结果
		try {
			if(!StringUtil.isNullOrEmpty(startDate)){
				StartDate = sdf.parse(startDate);
			}
			if(!StringUtil.isNullOrEmpty(endDate)){
				EndDate=sdf.parse(endDate);
			}
			promap.put("StartDate",StartDate);
	    	promap.put("EndDate",EndDate);
	    	promap.put("HotelKey",hotelKey);
	    	promap.put("ReserveType",reserveType);
	    	promap.put("RoomTypeID",roomTypeID);
	    	promap.put("CouponCode",couponCode);
	    	promap.put("FreeRoomCode",freeRoomCode);
	    	promap.put("RoomNum",roomNum);
	    	String json=getHttpJson("Logistics/HOS/GetOrdPrice",GsonUtil.toJson(promap),request,false);
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			double stateID=(Double) map.get("stateID");
			if(stateID==0&&(Double)map.get("businessState")==0){
				List<Map<String,Object>> priceDetailList=(List<Map<String,Object>>)map.get("PriceDetailList");
				for(Map<String,Object> price:priceDetailList){
					//String dateStr=sdf.format((Date)price.get("CostDate"));
					String dateStr=(String)price.get("CostDate");
					price.put("DateStr", dateStr.substring(0,(dateStr.indexOf(" "))));
					String TotalPriceStr = map.get("TotalPrice").toString();
					if(TotalPriceStr.indexOf(".0")>-1){
						TotalPriceStr = TotalPriceStr.substring(0,TotalPriceStr.indexOf(".0"));
						map.put("TotalPrice",TotalPriceStr);
					}

				}
				map.put("PriceDetailList", priceDetailList);
				return GsonUtil.toJson(map);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return "error";
    }
    
    //回调方法，未应用
    @RequestMapping(value = "/wxPayCallback",produces="text/html;charset=UTF-8;")
    @ResponseBody
    public String wxPayCallback(HttpServletRequest request, HttpServletResponse response) {
        String xmlBack="";
        try{
            InputStream is = request.getInputStream();
            //将InputStream转换成String
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
                String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return result;
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String notifyData=sb.toString();
            
            Map<String, String> notifyMap = null;
            IWxPayConfig config = new IWxPayConfig();
            WXPay wxpay = new WXPay(config);
            notifyMap = WXPayUtil.xmlToMap(notifyData);         // 转换成map
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
                // 签名正确
                // 进行处理。
                // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
                String out_trade_no = notifyMap.get("out_trade_no");//订单号
                if (out_trade_no == null) {
                	System.out.println("微信支付回调失败订单号:"+ notifyMap);
                    xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[微信支付回调失败订单号]]></return_msg>" + "</xml> ";
                    return xmlBack;
                }
                //TODO 业务逻辑处理 ****************************
                
                xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                return xmlBack;
            } else {
            	System.out.println("微信支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[微信支付回调通知签名错误]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        }catch (Exception e){
            e.printStackTrace();
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }
	/**
	 * 收藏/取消收藏
	 * @return
	 */
    @RequestMapping(value = "/hotelCollection",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String hotelCollection(HttpServletRequest request,String type,String hotelKey){
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("HotelKey",hotelKey);
		String json="";
		if("1".equals(type)){
			json=getHttpJson("Logistics/MEM/HotelCollection",GsonUtil.toJson(promap),request,false);
		}else{
			json=getHttpJson("Logistics/MEM/CancelHotelCollection",GsonUtil.toJson(promap),request,false);
		}
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			double stateID=(Double) map.get("stateID");
			if(stateID==0&&(Double)map.get("businessState")==0){
				return "success";
			}else{
				return (String)map.get("msgInfo");
			}
		}else{
			return "error";
		}
	}
	/**
	 * 我的收藏
	 * @return
	 */
    @RequestMapping("/collection")
    public ModelAndView collection(HttpServletRequest request,Integer pageSize,Integer pageIndex){
    	ModelAndView md=new ModelAndView("collection");
    	List<Map<String,Object>> holtels=new ArrayList<Map<String,Object>>();
    	Map<String,Object> promap=new HashMap<String,Object>();
    	if(pageIndex==null){
			pageIndex=1;
		}
		if (pageSize==null){
			pageSize = 1000;
		}
    	promap.put("PageIndex",pageIndex);
    	promap.put("PageSize",pageSize);
    	String hotelJson=getHttpJson("Logistics/MEM/QueryHotelCollection",GsonUtil.toJson(promap),request,false);
    	if(hotelJson!=null){
			Map<String,Object> map=GsonUtil.fromJson(hotelJson,new TypeToken<Map<String, Object>>(){}.getType());
			if(map.get("stateID")!=null && (Double)map.get("stateID")==0 && map.get("businessState")!=null &&(Double)map.get("businessState")==0 && !"".equals(map.get("dataList"))){
				holtels=(List<Map<String, Object>>) map.get("dataList");
				for(Map<String, Object> holtel:holtels){
					if(holtel.get("StartPrice").toString().indexOf(".0")>-1){
						holtel.put("StartPrice",holtel.get("StartPrice").toString().substring(0,holtel.get("StartPrice").toString().indexOf(".0")));
					}
					if(holtel.get("BreakfastPrice").toString().indexOf(".0")>-1){
						holtel.put("BreakfastPrice",holtel.get("BreakfastPrice").toString().substring(0,holtel.get("BreakfastPrice").toString().indexOf(".0")));
					}
					Double Distance=(Double)holtel.get("Distance");
					if(Distance!=null&&Distance!=0){
						if(Distance>10000000){
							holtel.put("Distance",new BigDecimal(Distance/10000000).setScale(2, BigDecimal.ROUND_HALF_UP)+"万公里");
						}else if(Distance>1000){
							holtel.put("Distance",new BigDecimal(Distance/1000).setScale(2, BigDecimal.ROUND_HALF_UP)+"公里");
						}else{
							holtel.put("Distance",Integer.parseInt(Distance+"")+"米");
						}
					}else{
						holtel.put("Distance","em");
					}
				}
			}
    	}
    	md.addObject("holtels",holtels);
    	return md;
    }
    /**
	 * 酒店详情
	 * @return
	 */
    @RequestMapping(value = "/getRoomDetailInfo",produces="text/html;charset=UTF-8;")
    @ResponseBody
	public String getRoomDetailInfo(HttpServletRequest request,String roomId){
		Map<String,Object> promap=new HashMap<String,Object>();
		promap.put("RoomTypeID",roomId);
		String json=getHttpJson("Logistics/HOS/GetRoomDetailInfo",GsonUtil.toJson(promap),request,false);
		if(json!=null){
			Map<String,Object> map=GsonUtil.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
			double stateID=(Double) map.get("stateID");
			if(stateID==0&&(Double)map.get("businessState")==0){
				return json;
			}else{
				return "error";
			}
		}else{
			return "error";
		}
	}
    //=====================================未开发=================================================
	/**
	 * 设置页面
	 * @return
	 */
    @RequestMapping("/setUp")
    public String setUp(HttpServletRequest request){
    	return "setUp";
    }

    /**
	 * 会员权益
	 * @return
	 */
    @RequestMapping("/interestsMember")
    public String interestsMember(HttpServletRequest request){
    	return "interestsMember";
    }
}
